package com.star.security.authentication;

import com.star.security.context.ResponseToken;
import com.star.security.context.TokenContextHolder;
import com.star.security.context.TokenRepository;

import javax.servlet.http.HttpServletRequest;

/**
 * @author yangzj
 */
public class AuthenticationServiceImpl implements AuthenticationService {

    private final TokenRepository tokenRepository;
    private final AuthenticationManager authenticationManager;

    public AuthenticationServiceImpl(TokenRepository tokenRepository, AuthenticationManager authenticationManager) {
        this.tokenRepository = tokenRepository;
        this.authenticationManager = authenticationManager;
    }

    @Override
    public ResponseToken login(Authentication authentication) {
        Authentication authenticate = authenticationManager.authenticate(authentication);
        // 登录成功后可以切面可以获取用户数据
        TokenContextHolder.setContext(authenticate);
        return tokenRepository.save(authenticate);
    }

    @Override
    public void logout(HttpServletRequest request) {
        tokenRepository.remove(request);
    }

    @Override
    public void logout(Authentication authentication) {
        tokenRepository.remove(authentication);
    }

    @Override
    public void refresh(Authentication authentication) {
        tokenRepository.refresh(authentication);
    }
}
